package org.bit.lesson09;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    // 定义阻塞队列组织任务
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public MyThreadPool(int threadNum) {
        if (threadNum <= 0) {
            throw new IllegalArgumentException("线程数量必须大于0");
        }
        // 创建线程
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(() -> {
                // 不停扫描队列
                while (true) {
                    try {
                        // 从队列中取出任务
                        Runnable runnable = queue.take();
                        // 执行任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            // 启动线程
            thread.start();
        }
    }

    // 向线程池中提交任务
    public void submit (Runnable runnable) throws InterruptedException {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为空.");
        }
        // 向队列中添加任务
        queue.put(runnable);
    }
}
